package com.hymjweb.demo.hymj.system_maintenance.role_permission.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.sys.SysConstant;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.hymj.system_maintenance.permission.bean.PermissionPojo;
import com.hymjweb.demo.hymj.system_maintenance.permission.service.PermissionService;
import com.hymjweb.demo.hymj.system_maintenance.role_permission.bean.RolePermissionPojo;
import com.hymjweb.demo.hymj.system_maintenance.role_permission.mapper.RolePermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: demo
 * @BelongsPackage: com.hymjweb.demo.hymj.system_maintenance.role_permission.service
 * @Author: luoge
 * @CreateTime: 2021-03-23 18:50
 * @Description:
 */
@Service
public class RolePermissionService extends BaseService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionService permissionService;

    /**
     * 根据角色ID查询角色权限列表
     *
     * @param roleId
     * @return
     */
    public List<RolePermissionPojo> getRolePermissionListByRoleId(String roleId) {
        if (DataTypeUtil.isEmptyStr(roleId)) {
            return null;
        }

        return rolePermissionMapper.getRolePermissionListByRoleId(roleId);
    }

    public List<RolePermissionPojo> queryRolePermissionByRoleIdAndResourceTypeId(String roleId, Long resourceTypeId) {
        if (DataTypeUtil.isEmptyStr(roleId) || resourceTypeId == null) {
            return null;
        }

        List<RolePermissionPojo> rolePermissionPojoList = rolePermissionMapper.queryRolePermissionByRoleIdAndResourceTypeId(roleId, resourceTypeId);
        return rolePermissionPojoList;
    }

    /**
     * 根据用户角色 ids  'id1','id2' 加载对应的角色授权资源
     *
     * @param userRoleIds
     * @return
     */
    public List<RolePermissionPojo> getRolePermissionListByRoleIds(String userRoleIds) {
        return rolePermissionMapper.getRolePermissionListByRoleIds(userRoleIds);
    }


    public List<PermissionPojo> convertToJavaPojo(JSONArray jsonArray) {

        if (jsonArray == null || jsonArray.isEmpty()) {
            return null;
        }

        List<PermissionPojo> permissionPojoList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject permissionObj = jsonArray.getJSONObject(i);

            String id = permissionObj.getString("id");
            String pid = permissionObj.getString("pid");
            String pids = permissionObj.getString("pids");
            String name = permissionObj.getString("name");
            Long resourceTypeId = permissionObj.getLong("resourceTypeId");
            String url = permissionObj.getString("url");
            String permissionCode = permissionObj.getString("permissionCode");
            String menuId = permissionObj.getString("menuId");
            String menuName = permissionObj.getString("menuName");

            PermissionPojo pojo = new PermissionPojo();
            pojo.setId(id);
            ;
            pojo.setPid(pid);
            pojo.setPids(pids);
            pojo.setName(name);
            pojo.setResourceTypeId(resourceTypeId);
            pojo.setUrl(url);
            pojo.setPermissionCode(permissionCode);
            pojo.setMenuId(menuId);
            pojo.setMenuName(menuName);

            permissionPojoList.add(pojo);
        }
        return permissionPojoList;
    }

    @Transactional(rollbackFor = {Exception.class})
    public int addRoleMenuPermission(JSONObject roleMenuPermissionJsonObj) throws Exception {

        if (roleMenuPermissionJsonObj == null || roleMenuPermissionJsonObj.isEmpty()) {
            throwException("角色菜资源授权参数错误");
        }

        String roleId = roleMenuPermissionJsonObj.getString("roleId");
        if (DataTypeUtil.isEmptyStr(roleId)) {
            throwException("角色菜资源授权角色ID丢失!");
        }

        JSONArray permissionArray = roleMenuPermissionJsonObj.getJSONArray("permissionArray");
        if (permissionArray == null || permissionArray.isEmpty()) {
            throwException("角色菜资源授权无选择的菜单资源!");
        }

        List<PermissionPojo> permissionPojoList = convertToJavaPojo(permissionArray);

        // 通过循环来实现添加
        if (permissionPojoList == null && permissionPojoList.isEmpty()) {
            throw new Exception("角色菜资源授权无选择的菜单资源!");
        }

        // 1.根据角色 ID 与菜单位资源类型，删除所有已经存在资源
        int deleteAffectRows = rolePermissionMapper.deleteByRoleIdAndResourceTypeId(roleId, SysConstant.XT_DIC_PERMISSION_TYPE.MEMU.getId());

        List<RolePermissionPojo> rolePermissionPojoList = new ArrayList<>();
        // 构建插入对象
        for (PermissionPojo pojo : permissionPojoList) {
            RolePermissionPojo rolePermissionPojo = new RolePermissionPojo();
            rolePermissionPojo.setId(this.getSysStrId());
            rolePermissionPojo.setRoleId(roleId);
            rolePermissionPojo.setPermissionId(pojo.getId());
            rolePermissionPojo.setResourceTypeId(SysConstant.XT_DIC_PERMISSION_TYPE.MEMU.getId());
            rolePermissionPojoList.add(rolePermissionPojo);
        }

        // 批量插入
        int insertAffectRows = rolePermissionMapper.batchInsert(rolePermissionPojoList);

        return insertAffectRows;
    }




    @Transactional(rollbackFor = {Exception.class})
    public int saveRoleButtonPermission(JSONObject jsonObject) throws Exception {

        if (jsonObject == null || jsonObject.isEmpty()) {
            throwException("保存角色按钮授权参数错误!");
        }

        List<RolePermissionPojo> rolePermissionPojoList = new ArrayList<>();

        String roleId = jsonObject.getString("roleId");
        JSONArray jsonArray = jsonObject.getJSONArray("rolePermission");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            /**
             * id: "439874861879676946"
             * menuId: "01100"
             * menuName: "数据字典"
             * name: "新建一级节点"
             * permissionCode: "xtdic:addLevel1Node"
             * pid: null
             * pids: null
             * resourceTypeId: 602
             */
            String permissonId = object.getString("id");
            Long resourceTypeId = object.getLong("resourceTypeId");

            RolePermissionPojo pojo = new RolePermissionPojo();
            pojo.setId(this.getSysStrId());
            pojo.setRoleId(roleId);
            pojo.setPermissionId(permissonId);
            pojo.setResourceTypeId(resourceTypeId);

            rolePermissionPojoList.add(pojo);
        }

        if (rolePermissionPojoList.isEmpty()) {
            return SysConstant.INT_ZERO;
        }

        // 1.先根据指定的角色与资源类型删除之前对应的资源
        int deleteAffectRows = rolePermissionMapper.deleteByRoleIdAndResourceTypeId(roleId, SysConstant.XT_DIC_PERMISSION_TYPE.BUTTON.getId());

        // 2.保存新的资源
        int affectRows = rolePermissionMapper.batchInsert(rolePermissionPojoList);

        return affectRows;
    }
}
